$(function() {

    $(".form-myt-distribute-delivery-bpmInput").data("formOptions", {
        updateTotalAmount : function() {
            var $form = $(this);

            var $grid = $form.find(".grid-myt-distribute-delivery-bpmInput");
            var userData = {
                "commodity.display" : "合计："
            };
            // 更新表格汇总统计数据

            userData.quantity = $grid.jqGrid('sumColumn', 'quantity');
            userData.taxAmount = $grid.jqGrid('sumColumn', 'taxAmount');
            userData.amount = $grid.jqGrid('sumColumn', 'amount');
            userData.originalAmount = $grid.jqGrid('sumColumn', 'originalAmount');
            userData.discountAmount = $grid.jqGrid('sumColumn', 'discountAmount');

            $grid.jqGrid("footerData", "set", userData, true);

            var chargeLogisticsAmount = Util.parseFloatValDefaultZero($form.find("input[name='chargeLogisticsAmount']"));
            var discountAmount = Util.parseFloatValDefaultZero($form.find("input[name='discountAmount']"))
            var commodityAmount = userData.amount;
            var totalTaxAmount = userData.taxAmount;
            var commodityAndTaxAmount = commodityAmount + totalTaxAmount;
            var totalAmount = commodityAndTaxAmount + chargeLogisticsAmount;
            $form.setFormDatas({
                commodityAmount : commodityAmount,
                totalTaxAmount : totalTaxAmount,
                commodityAndTaxAmount : commodityAndTaxAmount,
                discountAmount : userData.discountAmount,
                totalOriginalAmount : userData.originalAmount,
                totalAmount : totalAmount,
                payedAmount : totalAmount
            });
        },
        bindEvents : function() {
            var $form = $(this);
            var $grid = $form.find(".grid-myt-distribute-delivery-bpmInput");

            $form.find('input[name="agentPartner.display"]').on("treeselect.nodeSelect", function(event, treeNode) {
                $form.setFormDatas({
                    'receivePerson' : treeNode.contactPerson,
                    'mobilePhone' : treeNode.contactPhone,
                    'deliveryAddr' : treeNode.address,
                    'postCode' : treeNode.postCode
                });
                var level = treeNode.level+1;
                $grid.attr("data-agentLevel",level);
                
                /**
                 * 动态切换商品单价，根据所选的代理商等级
                 */
                // 1. 首先取消行编辑状态，如果有的话
                $grid.closest("div.ui-jqgrid-view").find(".ui-pg-div span.ui-icon-cancel").click();
                // 2. 遍历行项数据替换相应的价格字段，重新计算总金额等字段
                var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                for (i = 0; i < ids.length; i++) {
                    var row = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                    if(row['commodity.id'].length > 0){// 商品ID为空，判定为空行，空行不做处理
                        row['price'] = row['level'+level+'AgentSalePrice'];// 替换为代理商等级对应的单价
                        // 计算当前行的数据
                        $grid.data("gridOptions").calcRowAmount.call($grid, row);
                        $grid.jqGrid("setRowData", ids[i], row);
                    }
                }
                // 统计表格数据
                $form.data("formOptions").updateTotalAmount.call($form);
            });

            $form.find("input[name='chargeLogisticsAmount']").keyup(function() {
                $form.data("formOptions").updateTotalAmount.call($form);
            });

            Biz.setupCustomerProfileSelect($form);

            //按金额自动分摊折扣金额
            $form.find(".btn-discount-by-amount").click(function() {
                if ($grid.jqGrid("isEditingMode", true)) {
                    return false;
                }
                //按照“原价金额”的比率计算更新每个行项的折扣额，注意最后一条记录需要以减法计算以修正小数精度问题
                var discountAmount = $form.find("input[name='discountAmount']").val();
                var totalOriginalAmount = $grid.jqGrid('sumColumn', 'originalAmount');
                var perDiscountAmount = MathUtil.mul(MathUtil.div(discountAmount, totalOriginalAmount, 5), 100);
                var lastrowid = null;
                var totalDiscountAmount = 0;
                var ids = $grid.jqGrid("getDataIDs");
                $.each(ids, function(i, id) {
                    var rowdata = $grid.jqGrid("getRowData", id);
                    if (rowdata['gift'] != 'true' && rowdata['commodity.id'] != '') {
                        rowdata['discountRate'] = perDiscountAmount;
                        $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'discountRate');
                        $grid.jqGrid('setRowData', id, rowdata);
                        totalDiscountAmount = MathUtil.add(totalDiscountAmount, rowdata['discountAmount']);
                        lastrowid = id;
                    }
                });
                //最后一条记录需要以减法计算以修正小数精度问题
                if (lastrowid) {
                    var rowdata = $grid.jqGrid("getRowData", lastrowid);
                    rowdata['discountAmount'] = MathUtil.sub(discountAmount, MathUtil.sub(totalDiscountAmount, rowdata['discountAmount']));
                    $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'discountAmount');
                    $grid.jqGrid('setRowData', lastrowid, rowdata);
                }

                $form.data("formOptions").updateTotalAmount.call($form);

            });

            //打印快递单
            $form.find(".btn_express_print_QF").click(function() {
                if (confirm("确认调用票据打印程序打印当前快递单吗?")) {
                    var url = WEB_ROOT + "/rpt/jasper-report!generate?format=XLS&report=EXPRESS_QUANFENG&contentDisposition=attachment";
                    url += "&reportParameters['SALE_DELIVERY_IDS']=" + $form.find("input[name='voucher']").val();
                    window.open(url, "_blank");
                }
            });
            $form.find(".btn_express_print_ST").click(function() {
                if (confirm("确认调用票据打印程序打印当前快递单吗?")) {
                    var url = WEB_ROOT + "/rpt/jasper-report!generate?format=XLS&report=EXPRESS_SHENTONG&contentDisposition=attachment";
                    url += "&reportParameters['SALE_DELIVERY_IDS']=" + $form.find("input[name='voucher']").val();
                    window.open(url, "_blank");
                }
            });
            //打印发货单
            $form.find(".btn_delivery_print").click(function() {
                if (confirm("确认打印发货清单?")) {
                    var url = WEB_ROOT + "/rpt/jasper-report!generate?format=XLS&report=SALE_DELIVERY_COMMODITY_LIST&contentDisposition=attachment";
                    url += "&reportParameters['SALE_DELIVERY_IDS']=" + $form.find("input[name='voucher']").val();
                    window.open(url, "_blank");
                }
            });

            $form.find("input[name='accountSubject.display']").treeselect({
                url : WEB_ROOT + "/myt/finance/account-subject!findPaymentAccountSubjects",
                callback : {
                    onSingleClick : function(event, treeId, treeNode) {
                        $form.setFormDatas({
                            'accountSubject.id' : treeNode.id,
                            'accountSubject.display' : treeNode.display
                        }, true);
                    },
                    onClear : function(event) {
                        $form.setFormDatas({
                            'accountSubject.id' : '',
                            'accountSubject.display' : ''
                        }, true);
                    }
                }
            });
        },
        preValidate : function() {
            var $form = $(this);
            var $payedAmount = $form.find("input[name='payedAmount']");
            var $paymentAccountSubjects = $form.find("input[name='accountSubject.id']");
            if ($payedAmount.val() != '' && $paymentAccountSubjects.val() == '') {
                bootbox.alert("如有收款金额则必须选取收款账户");
                return false;
            }
        }
    });

    $(".grid-myt-distribute-delivery-bpmInput").data("gridOptions", {
        calcRowAmount : function(rowdata, src) {
            rowdata['originalAmount'] = MathUtil.mul(rowdata['price'], rowdata['quantity']);
            if (src == 'discountAmount') {
                rowdata['discountRate'] = MathUtil.div(rowdata['discountAmount'], rowdata['originalAmount'], 5) * 100;
                rowdata['amount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['discountAmount']);
            } else if (src == 'amount') {
                rowdata['discountAmount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['amount']);
                rowdata['discountRate'] = MathUtil.div(rowdata['discountAmount'], rowdata['originalAmount'], 5) * 100;
            } else {
                rowdata['discountAmount'] = MathUtil.div(MathUtil.mul(rowdata['discountRate'], rowdata['originalAmount']), 100);
                rowdata['amount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['discountAmount']);
            }

            rowdata['taxAmount'] = MathUtil.div(MathUtil.mul(rowdata['amount'], rowdata['taxRate']), 100);
            rowdata['commodityAndTaxAmount'] = MathUtil.add(rowdata['amount'], rowdata['taxAmount']);
        },
        updateRowAmount : function(src) {
            var $grid = $(this);
            var rowdata = $grid.jqGrid("getEditingRowdata");
            $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, src);
            $grid.jqGrid("setEditingRowdata", rowdata);
        },
        batchEntitiesPrefix : "distributeDeliveryDetails",
        url : function() {
            var pk = $(this).attr("data-pk");
            if (pk) {
                return WEB_ROOT + "/myt/partner/distribute-delivery!details?id=" + pk + "&clone=" + $(this).attr("data-clone");
            }
        },
        colModel : [ {
            label : '所属销售单主键',
            name : 'saleDelivery.id',
            hidden : true,
            hidedlg : true,
            editable : true,
            formatter : function(cellValue, options, rowdata, action) {
                var pk = $(this).attr("data-pk");
                return pk ? pk : "";
            }
        }, {
            name : 'commodity.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'level1AgentSalePrice',
            hidden : true,
            hidedlg : true,
            editable : true
        },  {
            name : 'level2AgentSalePrice',
            hidden : true,
            hidedlg : true,
            editable : true
        },  {
            name : 'level3AgentSalePrice',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'boxOrderDetailCommodity.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'commodity.sku',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'commodity.barcode',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'commodityStock.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            label : '行项号',
            name : 'subVoucher',
            width : 50,
            editable : true,
            editrules : {
                required : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $el = $(elem);
                    if ($el.val() == '') {
                        var $jqgrow = $el.closest(".jqgrow");
                        var idx = $jqgrow.find(">td.jqgrid-rownum").html().trim();
                        $el.val(100 + idx * 10);
                    }
                }
            },
            align : 'center'
        }, {
            label : '商品',
            name : 'commodity.display',
            width : 200,
            editable : true,
            editrules : {
                required : true
            },
            editoptions : {
                placeholder : '输入商品信息提示选取或双击选取',
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    
                    // 弹出框的选取回调函数
                    var selectCommodity = function(item) {
                        var level = $grid.attr("data-agentLevel");// 获得商品的价格级别
                        
                        var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                        var existRowId = null;// 如果是已经选择过的商品，那么这是哪个商品的所在行行号
                        var oldQuantity = null;// 如果是已经选择过的商品，那么这是哪个商品的数量
                        for (i = 0; i < ids.length; i++) {
                            var row = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                            if(item['commodity.sku'] == row['commodity.sku'] && 
                                item.batchNo == row.batchNo && 
                                item['storageLocation.id'] == row['storageLocation.id'] && 
                                item.gift.toString() == row['gift'].toString()){
                                 // SKU，批次号，库存地一致，是否赠品一致即认为是同一商品
                                existRowId = ids[i];
                                oldQuantity = row.quantity;
                                break;
                            }
                        }

                        if (existRowId) {
                            $grid.jqGrid("setRowData", existRowId, {
                                'quantity' : MathUtil.add(oldQuantity, 1)
                            });
                            var myrowdata = $grid.jqGrid('getRowData', existRowId);//获取单行数据根据ID
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            $grid.jqGrid("setRowData", existRowId, myrowdata);
                        } else {
                            var myrowdata;
                            if(item.gift){
                                // 赠品
                                myrowdata = {
                                        'commodity.sku' : item['commodity.sku'],//商品唯一性标识
                                        'commodity.id' : item['commodity.id'],
                                        'commodity.barcode' : item['commodity.barcode'],
                                        'commodity.sku' : item['commodity.sku'],
                                        'commodity.display' : item['commodity.display'],
                                        'commodity.title' : item['commodity.title'],
                                        'measureUnit' : item['commodity.measureUnit'],
                                        'storageLocation.id' : item['storageLocation.id'],
                                        'batchNo' : item['batchNo'],
                                        'expireDate' : item['expireDate'],
                                        'quantity' : 1,
                                        'discountRate' : 0,
                                        'taxRate' : 17,
                                        'level1AgentSalePrice' : item['commodity.commodityVaryPrice.level1AgentSalePrice'],
                                        'level2AgentSalePrice' : item['commodity.commodityVaryPrice.level2AgentSalePrice'],
                                        'level3AgentSalePrice' : item['commodity.commodityVaryPrice.level3AgentSalePrice'],
                                        'gift' : item.gift,
                                        'price' : 0,
                                        'originalAmount' : 0,
                                        'discountRate' : 0,
                                        'discountAmount' : 0,
                                        'amount' : 0,
                                        'taxAmount' : 0,
                                        'commodityAndTaxAmount' : 0
                                    };
                            }else{
                                // 非赠品
                                myrowdata = {
                                        'commodity.sku' : item['commodity.sku'],//商品唯一性标识
                                        'commodity.id' : item['commodity.id'],
                                        'commodity.barcode' : item['commodity.barcode'],
                                        'commodity.sku' : item['commodity.sku'],
                                        'commodity.display' : item['commodity.display'],
                                        'commodity.title' : item['commodity.title'],
                                        'price' : item['commodity.commodityVaryPrice.level'+level+'AgentSalePrice'],
                                        'measureUnit' : item['commodity.measureUnit'],
                                        'storageLocation.id' : item['storageLocation.id'],
                                        'batchNo' : item['batchNo'],
                                        'expireDate' : item['expireDate'],
                                        'quantity' : 1,
                                        'discountRate' : 0,
                                        'taxRate' : 17,
                                        'level1AgentSalePrice' : item['commodity.commodityVaryPrice.level1AgentSalePrice'],
                                        'level2AgentSalePrice' : item['commodity.commodityVaryPrice.level2AgentSalePrice'],
                                        'level3AgentSalePrice' : item['commodity.commodityVaryPrice.level3AgentSalePrice']
                                    };
                            }
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            existRowId = $grid.jqGrid("insertNewRowdata", myrowdata);
                        }

                        var $form = $grid.closest("form");
                        $form.data("formOptions").updateTotalAmount.call($form);

                        var idx = $grid.find("tr[id='" + existRowId + "'] >td.jqgrid-rownum").html().trim();
                        $grid.jqGrid('setRowData', existRowId, {
                            subVoucher : 100 + idx * 10
                        });
                    }
                    // 自动完成框的选取回调函数
                    var autocompleteSelectCommodity = function(item) {
                        var level = $grid.attr("data-agentLevel");// 获得商品的价格级别
                        
                        var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                        var existRowId = null;// 如果是已经选择过的商品，那么这是哪个商品的所在行行号
                        for (i = 0; i < ids.length; i++) {
                            var row = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                            if(item['commodity.sku'] == row['commodity.sku'] && 
                                    '' == row.batchNo && 
                                    item['storageLocation.id'] == row['storageLocation.id'] && 
                                    row['gift'] == 'false'){
                                    // SKU，批次号，库存地一致，并且不是赠品即认为是同一商品
                                    // 因为自动完成功能所带数据一律没有批次号，所以有以空比较 ('' == row.batchNo)
                                existRowId = ids[i];
                                break;
                            }
                        }

                        if (existRowId) {
                            var myrowdata = $grid.jqGrid('getRowData', existRowId);//获取单行数据根据ID
                            alert("所选商品已存在[ "+myrowdata.subVoucher+" | "+myrowdata['commodity.display']+" ]，请直接编辑数量字段。");
                        } else {
                            var myrowdata = {
                                'commodity.sku' : item['commodity.sku'],//商品唯一性标识
                                'commodity.id' : item['commodity.id'],
                                'commodity.barcode' : item['commodity.barcode'],
                                'commodity.sku' : item['commodity.sku'],
                                'commodity.display' : item['commodity.display'],
                                'commodity.title' : item['commodity.title'],
                                'price' : item['commodity.commodityVaryPrice.level'+level+'AgentSalePrice'],
                                'measureUnit' : item['commodity.measureUnit'],
                                'storageLocation.id' : item['storageLocation.id'],
                                'batchNo' : item['batchNo'],
                                'expireDate' : item['expireDate'],
                                'quantity' : 1,
                                'discountRate' : 0,
                                'taxRate' : 17,
                                'level1AgentSalePrice' : item['commodity.commodityVaryPrice.level1AgentSalePrice'],
                                'level2AgentSalePrice' : item['commodity.commodityVaryPrice.level2AgentSalePrice'],
                                'level3AgentSalePrice' : item['commodity.commodityVaryPrice.level3AgentSalePrice']
                            };
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            existRowId = $grid.jqGrid("setEditingRowdata", myrowdata);
                        }

                        var $form = $grid.closest("form");
                        $form.data("formOptions").updateTotalAmount.call($form);
                    }
                    $elem.dblclick(function() {
                        // 只有选了代理商，后面才能确定商品的价格级别
                        var agentPartner_id = $(".form-myt-distribute-delivery-bpmInput").find('input[name="agentPartner.display"]').val();
                        if (!agentPartner_id) {
                            alert("请先选择代理分销商！");
                            // 取消当前行编辑状态
                            $grid.closest("div.ui-jqgrid-view").find(".ui-pg-div span.ui-icon-cancel").click();
                            return;
                        }
                        var isGift = $(this).closest("tr").find("input[name='gift']").is(":checked");
                        var rowdata = $grid.jqGrid("getEditingRowdata");
                        $(this).popupDialog({
                            url : WEB_ROOT + '/myt/stock/commodity-stock!forward?_to_=selection&isGift='+isGift,
                            postData : {
                                sku : rowdata['commodity.sku']
                            },
                            title : '选取库存商品',
                            callback : function(item) {
                                selectCommodity(item);
                            }
                        })
                        // 多选模式双击弹出选取框之后，取消当前行编辑状态
                        $grid.closest("div.ui-jqgrid-view").find(".ui-pg-div span.ui-icon-cancel").click();
                    }).autocomplete({
                        autoFocus : true,
                        source : function(request, response) {
                            var data = Biz.queryCacheCommodityDatas(request.term);
                            return response(data);
                        },
                        minLength : 2,
                        select : function(event, ui) {
                            // 只有选了代理商，后面才能确定商品的价格级别
                            var agentPartner_id = $(".form-myt-distribute-delivery-bpmInput").find('input[name="agentPartner.display"]').val();
                            if (!agentPartner_id) {
                                alert("请先选择代理分销商！");
                                // 取消当前行编辑状态
                                $grid.closest("div.ui-jqgrid-view").find(".ui-pg-div span.ui-icon-cancel").click();
                                return;
                            }
                            var item = ui.item;
                            this.value = item.display;

                            autocompleteSelectCommodity(item);
                            event.stopPropagation();
                            event.preventDefault();
                            return false;
                        },
                        change : function(event, ui) {
                            if (ui.item == null || ui.item == undefined) {
                                //$elem.val("");
                                $elem.focus();
                            }
                        }
                    }).focus(function() {
                        $elem.select();
                    });
                }
            },
            align : 'left'
        }, {
            label : '单位',
            name : 'measureUnit',
            editable : true,
            width : 80
        }, {
            label : '数量',
            name : 'quantity',
            width : 80,
            formatter : 'number',
            editable : true,
            editrules : {
                required : true,
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            summaryType : 'sum'
        }, {
            label : '销售单价',
            name : 'price',
            width : 80,
            formatter : 'currency',
            editable : true,
            editrules : {
                required : true,
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            summaryType : 'sum'
        }, {
            label : '是否赠品',
            name : 'gift',
            width : 80,
            edittype : 'checkbox',
            editable : true,
            align : 'center',
            responsive : 'sm',
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    var $form = $elem.closest("form");
                    $elem.change(function() {
                        var checked = $elem.is(":checked");
                        /*
                         * 设置赠品或者取消赠品之后可能存在重复商品，所以在此校验唯一性
                         */
                        var editingRowData = $grid.jqGrid('getEditingRowdata');
                        var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                        for(i=0; i<ids.length; i++){
                            var existRowData = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                            if(editingRowData['commodity.sku'] == existRowData['commodity.sku']){
                                console.info(checked+" | "+existRowData['gift']);
                                if(checked.toString() == existRowData['gift']){
                                    // SKU一致，并且不是赠品即认为是同一商品
                                    alert("商品已存在[ "+existRowData.subVoucher+" | "+existRowData['commodity.display']+" ]," +
                                            "请尝试先删除此行，然后编辑已存在行的数量字段。");
                                    $elem.attr("checked", !checked);
                                    return;
                                }
                            }
                        }
                        
                        var bakNode = $elem.closest('tr');// 数据备份到的节点
                        if (checked) {
                            var rowdata = $grid.jqGrid("getEditingRowdata");
                            bakNode.attr("data-bak", JSON.stringify(rowdata));//先备份数据
                            rowdata['price'] = 0;
                            rowdata['originalAmount'] = 0;
                            rowdata['discountRate'] = 0;
                            rowdata['discountAmount'] = 0;
                            rowdata['amount'] = 0;
                            rowdata['taxAmount'] = 0;
                            rowdata['commodityAndTaxAmount'] = 0;
                            $grid.jqGrid("setEditingRowdata", rowdata);
                        }else{
                            // 取消赠品勾选后还原数据
                            rowdata = JSON.parse(bakNode.attr("data-bak"));
                            $grid.jqGrid("setEditingRowdata", rowdata);
                        }
                    });

                }
            },
        }, {
            label : '原始金额',
            name : 'originalAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        }, {
            label : '折扣率(%)',
            name : 'discountRate',
            width : 80,
            formatter : 'currency',
            editable : true,
            editrules : {
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '折扣额',
            name : 'discountAmount',
            width : 80,
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                    });
                }
            },
            align : 'right',
            responsive : 'sm'
        }, {
            label : '折后金额',
            name : 'amount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '税率(%)',
            name : 'taxRate',
            width : 80,
            formatter : 'number',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    var $form = $elem.closest("form");
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '税额',
            name : 'taxAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        }, {
            label : '含税总金额',
            name : 'commodityAndTaxAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        }, {
            label : '发货仓库',
            name : 'storageLocation.id',
            width : 150,
            editable : true,
            editrules : {
                required : true
            },
            stype : 'select',
            searchoptions : {
                value : Biz.getStockDatas()
            }
        }, {
            label : '批次号',
            name : 'batchNo',
            width : 80,
            editable : true,
            editoptions : {
                placeholder : '双击选取',
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.dblclick(function() {
                        $elem.closest(".jqgrow").find("input[name='commodity.display']").dblclick();
                    }).keypress(function(event) {
                        return false;
                    });
                }
            }
        }, {
            label : '批次过期日期',
            name : 'expireDate',
            width : 80,
            editable : true,
            editoptions : {
                readonly : true,
                placeholder : '双击选取',
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.dblclick(function() {
                        $elem.closest(".jqgrow").find("input[name='commodity.display']").dblclick();
                    }).keypress(function(event) {
                        return false;
                    });
                }
            }
        } ],
        footerrow : true,
        beforeInlineSaveRow : function(rowid) {
            var $grid = $(this);
            $grid.data("gridOptions").updateRowAmount.call($grid);
        },
        afterInlineSaveRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
        },
        afterInlineDeleteRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
        },
        userDataOnFooter : true
    });

});
